package cn.itchao.example.goods.service;

import cn.itchao.example.goods.domain.Goods;
import cn.itchao.example.goods.rest.MemberDubboRestService;
import cn.itchao.example.goods.rest.MemberRestService;
import cn.itchao.example.member.api.MemberServiceApi;
import cn.itchao.example.member.dto.MemberDto;
import cn.itchao.exmaple.base.ApiResponse;
import cn.itchao.exmaple.base.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.DataInput;
import java.io.IOException;
import java.util.LinkedHashMap;

@Service
public class GoodsService {

    @Reference(protocol = "dubbo",check = false,timeout = 10000)
    private MemberServiceApi memberServiceApi;

    @Autowired
    @Lazy
    private MemberRestService memberRestService;

    @Autowired
    @Lazy
    private MemberDubboRestService memberDubboRestService;

    public MemberDto findMemberDubboById(Long id){

        ApiResponse<MemberDto> apiResponse = memberServiceApi.findMemberById(id);
        if(apiResponse.getCode() == 200){
            return apiResponse.getData();
        }
        return null;
    }

    public MemberDto findMemberRestById(Long id) throws IOException {
        ApiResponse apiResponse = memberRestService.findMemberById(id);
        if(apiResponse.getCode() == 200){
            LinkedHashMap<String,Object> data = (LinkedHashMap<String, Object>) apiResponse.getData();
            MemberDto memberDto = JsonUtils.convertValue(data, MemberDto.class);
            return memberDto;
        }
        return null;
    }

    public MemberDto findMemberDubboRestById(Long id) throws IOException {
        ApiResponse apiResponse = memberDubboRestService.findMemberById(id);
        if(apiResponse.getCode() == 200){
            LinkedHashMap<String,Object> data = (LinkedHashMap<String, Object>) apiResponse.getData();
            MemberDto memberDto = JsonUtils.convertValue(data, MemberDto.class);
            return memberDto;
        }
        return null;
    }

    public Goods findGoodsById(Long id) {
        Goods goods = new Goods();
        goods.setId(id);
        goods.setName("毛巾");
        goods.setType(1);
        return goods;
    }
}
